<template>
  <div class="main-container">
    <div class="header">
      <div class="search" style="margin-bottom: 30px;">
          <label><strong>搜索学生：</strong></label>
          <el-input placeholder="请输入内容" v-model="input" class="input-with-select">
              <el-select v-model="select" slot="prepend" placeholder="请选择" class="select-with-input">
                  <el-option label="学号" value="1"></el-option>
                  <el-option label="身份证号" value="2"></el-option>
                  <el-option label="银行卡号" value="3"></el-option>
              </el-select>
              <el-button icon="el-icon-picture"  slot="append" @click="showUploadDialog" class="custom-btn" :loading="loading">图片识别</el-button>
              <el-button icon="el-icon-search"  slot="append" @click="search" class="custom-btn"></el-button>
          </el-input>
      </div>
  </div>
  <!-- 弹出上传窗口 -->
  <el-dialog
    title="图片上传"
    :visible.sync="uploadDialogVisible"
    width="50%"
  >
  <el-upload
    class="upload-demo"
    action=""
    :on-remove="handleRemove"
    :file-list="fileList"
    list-type="picture"
    :before-upload="beforeUpload"
    :http-request="handleFileChange"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传 jpg/png 文件，且不超过 5000KB</div>
  </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="uploadDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleUpload">识别</el-button>
    </span>
  </el-dialog>
    <div class="info">
      <div class="info-table">
    <table>
      <thead>
        <tr>
          <th style="width: 120px;">姓名</th>
          <th style="width: 120px;">手机号</th>
          <th style="width: 100px;">学号</th>
          <th style="width: 200px;">身份证号</th>
          <th style="width: 200px;">银行卡号</th>
          <th style="width: 280px;">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentPageData" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.phone }}</td>
          <td>{{ item.id }}</td>
          <td>{{ item.idCard }}</td>
          <td>{{ item.bankCard }}</td>
          <td>
              <el-button type="primary" @click="openModal(item)" class="button">短信发送</el-button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
    </div>
    <div class="footer">
          <el-button type="primary" :disabled="currentPage === 1" @click="changePage(currentPage - 1)" icon="el-icon-arrow-left"></el-button>
          <span>&emsp;第 {{ currentPage }} 页&emsp;</span>
          <el-button type="primary" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)" icon="el-icon-arrow-right"></el-button> 
    </div>
    <el-dialog
  title="选择短信模板"
  :visible.sync="dialogVisible"
  width="40%"
  @close="resetForm"
>
  <el-form :model="smsForm">
    <el-form-item label="短信类型">
      <el-radio-group v-model="smsForm.type" @change="updateSmsContent">
        <el-radio label="studentCard">学生证</el-radio>
        <el-radio label="bankCard">银行卡</el-radio>
        <el-radio label="idCard">身份证</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="地址">
      <el-input placeholder="请输入认领地址" v-model="smsForm.address" @input="updateSmsContent"></el-input>
    </el-form-item>
    <!-- 短信预览区域 -->
    <el-form-item label="短信内容预览">
      <el-input type="textarea" :value="smsForm.smscontent" readonly placeholder="短信内容预览" rows="4"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取消</el-button>&emsp;
    <el-popconfirm
      confirm-button-text='确认'
      cancel-button-text='取消'
      icon="el-icon-info"
      title="请再次确认短信发送内容"
      @confirm="sendSms"
    >
      <el-button type="primary" slot="reference" v-loading.fullscreen.lock="fullscreenLoading">发送短信</el-button>
    </el-popconfirm>
  </span>
</el-dialog>
  </div>
  
</template>

<script>
import axios from 'axios';
import Tesseract from 'tesseract.js';
export default {
  data() {
    return {
      input:'',
      select: '',
      uploadDialogVisible: false, // 控制弹出框的显示
      dialogVisible: false,
      selectedFilter: 'all',
      currentPage: 1,
      pageSize: 5, // 每页显示的条数
      totalItems: 0, 
      data: [], 
      fileList: [],
      fullscreenLoading: false,
      imageUrl: '',  // 存储临时生成的 URL 用于预览图片
      smsForm: {
      type: '',  // 短信类型，学生证、银行卡号或身份证号
      student: null, // 当前选择的学生信息
      address:'',
      smscontent:'',
      typeText:'',
      },
      loading:false
    };
  },
  methods: {
      confirmAction() {
          // 执行确定操作   
          console.log("确认操作");
      },    
      moreAction() {
          // 执行更多操作
          console.log("更多操作");
      },
      changePage(page) {
          if (page < 1 || page > this.totalPages) return; // Prevent going out of bounds
          this.currentPage = page;
      },
      // 进行搜索操作
      async search() {
        console.log(this.select,this.input);
        // 判断搜索字段和搜索值是否为空
        if (!this.select || !this.input) {
          this.$message.error('请选择搜索字段并输入搜索值');
          return;  // 如果为空，退出搜索函数
        }
        try {
          const params = {
            searchField: this.select, // 搜索字段，如：学号、身份证号、银行卡号
            searchValue: this.input, // 搜索值
            
          };
          const response = await axios.get('/api/student/search', { params });
          console.log(response.data);
          if (response.data.totalItems === 0) {
            this.$message.error('无结果');
            this.data = [];  // 清空结果数据
            this.totalItems = 0;  // 清空总条目数
            this.currentPage = 1;  // 重置当前页为第一页
          } else {
            this.$message.success('搜索成功');
            // 显示查询到的数据
            this.data = response.data.students;
            this.totalItems = response.data.totalItems;
          }
        } catch (error) {
          this.$message.error('搜索错误');
        }
      },
      // 打开模态对话框并传递当前学生数据
      openModal(student) {
        this.smsForm.student = student;
        this.smsForm.type = '{失物类型}';  // 默认短信类型
        this.smsForm.address = '';         // 初始地址为空
        this.smsForm.typeText = ''
        this.updateSmsContent();           // 立即更新短信内容
        this.dialogVisible = true;  // 显示对话框
      },
      // 重置表单
      resetForm() {
        this.smsForm.type = '';  // 清除短信类型
        this.smsForm.student = null;  // 清除当前学生信息
      },
      // 更新短信内容
  updateSmsContent() {
    const { student, type, address, typeText } = this.smsForm;
    
    // 根据 type 生成对应的短信内容
    switch (type) {
      case 'studentCard':
        this.smsForm.typeText = '学生证';
        break;
      case 'bankCard':
      this.smsForm.typeText = '银行卡';
        break;
      case 'idCard':
      this.smsForm.typeText = '身份证';
        break;
      default:
      this.smsForm.typeText = '{失物类型}';
        break;
    }
    // 动态生成短信内容
    this.smsForm.smscontent = `${student.name}同学,你的${typeText}被教职工捡到了，请到${address}认领。`;
  },
      async sendSms() {
        this.fullscreenLoading = true;
        setTimeout(() => {
          this.fullscreenLoading = false;
        }, 2000);
        const { student, type, address, smscontent, typeText} = this.smsForm;
        if (!type || !address) {
          this.$message.error('请选择短信类型并填写认领地址！');
          return;
        }
        // 根据 type 选择 num
        let num;
        switch (type) {
          case 'studentCard':
            num = student.id;  // 选择学号
            break;
          case 'bankCard':
            num = student.bankCard // 选择银行卡号
            break;
          case 'idCard':
            num = student.idCard;  // 选择身份证号
            break;
        }
    try {
      // 发送短信并更新 home 表的数据
      const response = await axios.post('/api/student/send-home', {
        id: student.id,
        name: student.name,
        phone: student.phone,
        type: typeText,
        num: num,
        address:address,
        smscontent: smscontent,});
        if (response.status === 200) {
            // 处理成功的情况
            this.$message.success('短信发送请求已接受，正在处理...');
            this.fetchHomeData(); // 更新数据
            this.$router.replace("/home"); // 跳转到 home 页面
        } else if (response.status === 500) {
            // 处理失败的情况
            this.$message.error('短信发送请求失败！');
        } else {
            // 如果有其他状态码
            this.$message.error('发生未知错误，请稍后再试！');
        }
    } catch (error) {
      console.error('短信发送失败:', error);
      this.$message.error('短信发送失败！');
    } 
  },
  // 获取 home 表数据，更新 home 页面显示的数据
  async fetchHomeData() {
    try { 
      const response = await axios.get('/api/student/get-home-data');
      this.$store.dispatch('updateHomeData', response.data); // 通过 Vuex 更新 home 数据
    } catch (error) {
      console.error('获取数据失败', error);
      this.$message.error('获取数据失败');
    }
  },
      // 显示上传弹窗
  showUploadDialog() {
    this.uploadDialogVisible = true;
  },
  // 上传前的回调
  beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt5M = file.size / 1024 / 1024 < 5;

    if (!isJPG && !isPNG) {
      this.$message.error('只能上传 JPG/PNG 文件');
      return false;
    }
    if (!isLt5M) {
      this.$message.error('上传文件大小不能超过 5MB!');
      return false;
    }
    return true;
  },
  // 删除文件时的处理
  handleRemove(file, fileList) {
    this.fileList = fileList;
  },
  handleFileChange({file, onSuccess}) {
    if (file) {
      const url = URL.createObjectURL(file);
      this.imageUrl = url;
      this.fileList = [{
        name: file.name,
        url: url,
        raw: file,
      }];
      // 通知上传完成
      onSuccess();
    }
  },
  // 点击上传按钮的处理函数
  handleUpload() {
    if (this.fileList.length > 0) {
      const file = this.fileList[0].raw;
      this.performOCR(file);
      this.loading=true;
    } else {
      this.$message.error('请先上传文件');
    }
    this.uploadDialogVisible = false;
    this.loading=false;
  },
  performOCR(file) {
    Tesseract.recognize(file, 'eng', {
      logger: (m) => console.log(m),
    }).then(({ data: { text } }) => {
      // 使用 trim 去除前后空格
      this.input = text.trim().replace(/\s+/g, ' '); // 去除多余的空格和换行符，保持单一空格分隔
      console.log('OCR识别结果:', this.input);
    }).catch((err) => {
      console.error(err);
      this.$message.error('OCR 识别失败');
    });
  },
  },
  computed: {
      totalPages() {
          return Math.ceil(this.totalItems / this.pageSize);
      },
      currentPageData() {
          const start = (this.currentPage - 1) * this.pageSize;
          const end = start + this.pageSize;
          return this.data.slice(start, end);
      },
},
};
</script>

<style scoped>
.main-container {
  padding: 20px;
  background-color: #f0f5ff;
}

h1 {
  font-size: 64px;
  font-weight: bold;
}
.info-table table {
  width: 80%;
  border-collapse: collapse;
  margin: auto;
}

.info-table th, .info-table td {
padding: 10px;
text-align: left;
}

.info-table th {
background-color: #f2f2f2;
color: #4578dc;
}
select {
  margin-left: 10px;
  padding: 5px;
  font-size: 14px;
  border-radius: 5px;
  border: 1px solid #ccc;
}
.switchs {
  text-align: left;
}
.footer {
font-size: 24px;
position: fixed;   /* 固定位置 */
bottom: 60px;      /* 离底部 60px */
left: 50%;         /* 水平居中 */
transform: translateX(-50%);  /* 精确居中 */
background-color: #fff;   /* 背景色，避免与内容重叠 */
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);  /* 为按钮添加阴影效果 */
z-index: 10;  /* 确保按钮在最上层 */
}
.search {
display: flex;          /* 使用 Flexbox 布局 */
align-items: center;    /* 垂直居中对齐 */
}

.search label {
margin-right: 10px;     /* 给 label 添加右边距，确保与输入框有间隔 */
}

.input-with-select {
  width: 50%;         /* 设置输入框的宽度 */
}

.search .el-button .el-input {
  margin: 10px auto;
}
.select-with-input {
width: 120px; /* 设置前置部分 el-select 的宽度 */
}

.custom-btn:hover {
background-color: #33a77b; /* 鼠标悬浮时的背景颜色 */
color: #000;
}
</style>
